#include <REGX52.H>
#include <INTRINS.h>
#include "Nixie.h"
#include "Delay.h"
#include "Key.h"
#include "Timer0.h"
#include "AT24C02.h"
#include "I2C.h"

unsigned char KeyNum;
//unsigned char Temp;
unsigned char Min,Sec,MinSec;
unsigned char RunFlag;
void main()
{
	  Timer0_Init();
		while(1)
		{
		  KeyNum = Key();
			if(KeyNum)//Temp=KeyNum;//如果KeyNum被按下就返回值并存在Temp 直接返回KeyNum我们之前清空了
				        //Nixie(1,Temp);
			{
			  if(KeyNum==1){RunFlag=!RunFlag;}//启动暂停
				if(KeyNum==2){Min=0;Sec=0;MinSec=0;}//清零
				if(KeyNum==3)//写入内存
         {
				   AT24C02_WriteByte(0,Min);
				   Delay(5);
			     AT24C02_WriteByte(1,Sec);
				   Delay(5);
				   AT24C02_WriteByte(2,MinSec);
				   Delay(5);
				 }
				if(KeyNum==4)//读出内存
         {
				   Min = AT24C02_ReadByte(0);
				   Sec = AT24C02_ReadByte(1);
					 MinSec = AT24C02_ReadByte(2);
				 
				 }
			}	
			    
		  	Nixie_SetBuf(1,Min/10);//分钟10位
				Nixie_SetBuf(2,Min%10);//分钟个位
				Nixie_SetBuf(3,11);
				Nixie_SetBuf(4,Sec/10);//秒10位
				Nixie_SetBuf(5,Sec%10);//秒个位
				Nixie_SetBuf(6,11);
				Nixie_SetBuf(7,MinSec/10);//不知道啥玩意10位 100 进 1
				Nixie_SetBuf(8,MinSec%10);//不知道啥玩意个位
		}
}
/**
  * @brief  秒表驱动函数，在中断中调用
  * @param  无
  * @retval 无
  */

void Sec_Loop(void)
{
	if(RunFlag)
	{
	MinSec++;
  if(MinSec>=100)
   {
	   MinSec=0;
		 Sec++;
		 if(Sec>=60)
		  {
			  Sec=0;
				Min++;
				if(Min>=60)
				 {
					 Min++;
				 }
			}
	 }

	}
  
}

void Timer0_Routine() interrupt 1
		{
			static unsigned int T0Count1,T0Count2,T0Count3;
			TL0 = 0x18;		  
			TH0 = 0xFC;
			
			T0Count1++;
			if(T0Count1>=20)//每隔20ms扫描一次按键
			{
				T0Count1=0;
		    Key_Loop();
		  }
			
			T0Count2++;
			if(T0Count2>=2)//每隔2ms扫描一下数码管
			{
				T0Count2=0;
		    Nixie_Loop();
		  }
			
			T0Count3++;
			if(T0Count3>=10)//每隔10ms扫描一下时间
			{
				T0Count3=0;
		    Sec_Loop();
		  }
			
	  }	